import pdb
import serial
import sys
p = serial.Serial(port=2, baudrate=1200, bytesize=serial.EIGHTBITS, parity=serial.PARITY_NONE, stopbits=serial.STOPBITS_ONE, timeout=0)
sys.stdout.write('port is opened\n')
sys.stdout.flush()


def parseContactId(raw):
    e = {}
    e['objId']      = raw[2:6]
    e['msgType']    = raw[6:7]
    e['msgCode']    = raw[7:10]
    e['group']      = raw[10:12]
    e['zone']       = raw[12:15]
    return e

message = ''
while (True):
    try:
        d = p.readline()
        p.write('\x06') #heartbeat
    
        if d == '': continue
        for i in d:
            if ord(i) in [20, 32]: 
                status = 'z '
                sys.stdout.write('\n')
                print parseContactId(message)
                message = ''
            else:
                status = 'o '
                message += i
        status += i + ' ' + message

        
        sys.stdout.flush()
    except Exception, err:
        sys.stdout.write('error: %s' % (str(err)))
        sys.stdout.flush()
        continue

p.close()
